home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: netcom.com!smryan
- From: smryan@netcom.com (@#$%!?!)
- Subject: Re: Reusable and Generic Functions
- Message-ID: <smryanDq6L1B.HIG@netcom.com>
- Organization: The Programmer formerly known as S M Ryan
- X-Newsreader: TIN [version 1.2 PL1]
- References: <4la9k2$76o@wormer.fn.net>
- Date: Sat, 20 Apr 1996 21:58:22 GMT
- Sender: smryan@netcom4.netcom.com
-
- : Is there a simple way to handle operations on both of those lists
- : using the same set of functions? Say for adding links we have this
- : function:
-
- Yes. You too can learn to abuse cpp in your own home.
-
- One way is to write a single define that can kill some compilers:
-
- #define generic(typename,datatype) \
- typedef struct typename { \
- datatype data; \
- struct typename *next; \
- } typename;\
- \
- typename *typename##_add(typename *next,datatype data) {\
- typename *temp = malloc(sizeof(typename)); \
- if (!temp) {...} \
- temp->data = data; \
- temp->next = next; \
- return next; \
- }\
- \
- void typename##_delete(typename *list) {\
- while (list) { \
- typename *next=list->next; \
- free(list); list = next; \
- } \
- }
-
- And then
- generic(FOO,int)
- will define FOO, FOO_add, and FOO_delete.
- generic(BAR,float)
- will define BAR, BAR_add, and BAR_delete.
-
-
- You can also put the code in another file so that generic.type is
-
- typedef struct typename{
- datatype data;
- struct typename *next;
- } typename;
-
- typename *addFunction(typename *next,datatype data) {
- ...
- }
- #ifdef deleteFunction
- typename *deleteFunction(typename *list) {
- ...
- }
- #endif
-
- and then instantiate with
-
- #define typename FOO
- #define datatype int
- #define addFunction sllist_add
- #include "generic.type"
- #undef typename
- #undef datatype
- #undef addFunction
-
- #define typename BAR
- #define datatype float
- #define addFunction barr_wed
- #define deleteFunction arnold_divorce
- #include "generic.type"
- #undef typename
- #undef datatype
- #undef addFunction
- #undef deleteFunction
- --
- The Queen who loves, the Queen of life, | smryan@netcom.com PO Box 1563
- the Queen who straits, the Queen of strife;| Cupertino, California
- with gasp of death or gift of breath | (xxx)xxx-xxxx 95015
- she brings the choice of birth or knife. | I don't use no smileys
-